﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Xml;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.AvalonEdit.Highlighting.Xshd;

namespace Oxage.CNC.Views
{
	public partial class LogView : UserControl
	{
		#region Constructor
		public LogView()
		{
			InitializeComponent();
			InitializeAvalonEdit();

			WriteLine("Logger initialized.");
		}
		#endregion

		#region Public methods
		public void WriteLine(string message)
		{
			if (message == null)
			{
				message = "null";
			}
			else
			{
				//Trim leading and trailing spaces and make 15 spaces padding on the left of each line
				message = message.Trim().Replace("\n", "\n" + "".PadLeft(15));
			}
			textEditor.Text += string.Format("[{0}] {1}{2}", DateTime.Now.ToString("HH:mm:ss.fff"), message, Environment.NewLine);
		}
		#endregion

		#region Protected methods
		protected void InitializeAvalonEdit()
		{
			try
			{
				IHighlightingDefinition loggerHighlighting;
				var info = Application.GetResourceStream(new Uri("Resources/Logger.xshd", UriKind.Relative));

				if (info == null || info.Stream == null)
				{
					throw new ArgumentNullException("stream", "Could not find embedded resource!");
				}

				using (XmlReader reader = new XmlTextReader(info.Stream))
				{
					loggerHighlighting = HighlightingLoader.Load(reader, HighlightingManager.Instance);
				}

				HighlightingManager.Instance.RegisterHighlighting("Log", new string[] { ".log" }, loggerHighlighting);

				textEditor.SyntaxHighlighting = loggerHighlighting;
				textEditor.TextChanged += (sender, e) =>
				{
					textEditor.ScrollToEnd();
				};
			}
			catch
			{
			}
		}
		#endregion
	}
}
